﻿using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
using System.Data.SqlClient;
using System.Linq;
using System.Reflection;
using System.Web;
using System.Web.Hosting;

namespace DYSales.Web
{
    public class conSQL
    {
        internal static string GetConString()
        {
            //express databse Data Source =.\SQLEXPRESS;
            return @"Data Source=.;Initial Catalog=" + Assembly.GetExecutingAssembly().GetName().Name + ".EntityContext;MultipleActiveResultSets=True;Persist Security Info=True;User ID=sa;Password=123456";
        }

        static SqlConnection conn;
        internal static SqlConnection GetConn()
        {
            Database.DefaultConnectionFactory = new SqlConnectionFactory(conSQL.GetConString());
            if (!Database.Exists(GetConString()))
            {
                Database.SetInitializer<EntityContext>(new SystemInitializer());
            }
            if (conn == null)
            {
                conn = new SqlConnection(GetConString());
                conn.Open();
            }
            return conn;
        }
        static SqlCommand cmdd;
        internal static void ExcuteSql(string sql)
        {
            if (cmdd == null)
            {
                cmdd = GetConn().CreateCommand();
            }
            cmdd.CommandText = sql;
            cmdd.ExecuteNonQuery();
        }

        internal static SqlDataReader ExcuteSqlReader(string sql)
        {
            if (cmdd == null)
            {
                cmdd = GetConn().CreateCommand();
            }
            cmdd.CommandText = sql;
            return cmdd.ExecuteReader();
        }

        internal static void Dispose()
        {
            try
            {
                conn.Close();
                conn.Dispose();
                conn = null;
            }
            catch { }
        }
    }
}